const query = require('../db/mysql')
const { success, error } = require('../model/model')
const {md5} = require('utility')
const jwt = require('jsonwebtoken')
class User {
    // 登录
    login = async (ctx) => {
        const { password, username } = ctx.request.body;
        let sql = `select * from users where username="${username}" and password="${md5(String(password))}"`
        const user = await query(sql)
        if(user.length) {
            ctx.body = success({
                data: user[0],
                token: jwt.sign({id:user[0].id}, '1812b')// 生成一个token
            }, '登陆成功')
        } else {
            ctx.body = error('请检查账号密码')
        }

    }
    // 注册
    register = async (ctx) => {
        // 
        const { password, username,nickname } = ctx.request.body;
        let sql = `select * from users where username="${username}" `
        const isHave = await query(sql)
        if (isHave.length) {
            ctx.body = error('账号已存在')
        } else {
            let userSql = `insert into users(username,password,nickname) values("${username}","${md5(String(password))}", "${nickname}")`
            const data = await query(userSql)
            if (data.affectedRows === 1) {
                ctx.body = success('注册成功')
            } else {
                ctx.body = error('注册失败')
            }
        }
    }
}

module.exports = new User()